package com.tongji.housediy.view.titlewindows
{
//	import com.adobe.net.URI;
	import com.tongji.housediy.events.UserLoadandRegisterEvent.UserRegisterEvent;
	
	import flash.events.MouseEvent;
	
	import mx.controls.Alert;
	import mx.core.FlexGlobals;
	import mx.managers.PopUpManager;
	
	import org.robotlegs.mvcs.Mediator;

	
	/**
	 * 
	 * @author songjia
	 * 2011/5/11
	 */ 
	public class RegisterTitleWinMediator extends Mediator
	{
		[Inject]
		public var view:RegisterTitleWindow;
		
		public function RegisterTitleWinMediator()
		{
			super();
		}
		
		public override function onRegister():void
		{
			view.closeBtn.addEventListener(MouseEvent.CLICK, closeBtnHandler);
			view.registerBtn.addEventListener(MouseEvent.CLICK, registerBtnHandler);
			view.regenerateCheckCode.addEventListener(MouseEvent.CLICK, regenerateCheckCode);
			view.checkCodeLal.text = generateCheckCode();
		}
		
		//生成随机码
		private function generateCheckCode():String
		{
			//初始化
			var ran:Number;
			var number:Number;
			var code:String;
			var checkCode:String = "";
			
			//生成四位随机数
			for(var i:int = 0; i < 4; i++)
			{
				ran = Math.random();
				number = Math.round(ran*10000);
				if(number % 2 == 0)
					//"0"的ASCII码是48  
					code = String.fromCharCode(48+(number % 10)); 
					//生成一个字母
				else  
					//"A"的ASCII码为65
					code = String.fromCharCode(65+(number % 26)) ;
				checkCode += code;
			}
			return checkCode;
		}
		
		public function closeBtnHandler(event:MouseEvent):void
		{
			PopUpManager.removePopUp(view);
		}
		
		public function registerBtnHandler(event:MouseEvent):void
		{
			if(view.userNameTX.text == "")
			{
				Alert.show("请输入完整数据");
			}
			else
			{
				if(view.checkCodeTX.text != view.checkCodeLal.text)
				{
					Alert.show("校验码错误!");
					//重新生成校验码
					view.checkCodeLal.text = generateCheckCode(); 
				}
				else if(EmailCheck() && passwordCheck())
				{
					dispatch(new UserRegisterEvent(UserRegisterEvent.USER_REGISTER, view.userNameTX.text, view.password.text, view.Email.text, "10.60"));
					PopUpManager.removePopUp(view);		
				}
			}						
		}
		
//		public function getIP():String//ip地址获取函数？？？？？？？？///未做测试
//		{
////			var uri:URI = new URI(FlexGlobals.topLevelApplication.url);
////			var IP:String = uri.authority;
//			//Alert.show("显示ip"+IP);
//			return IP;
//		}
//		
		public function EmailCheck():Boolean
		{
			for(var i:int = 0;i < view.Email.text.length; i++)
			{
				if(	view.Email.text.charAt(i)=='@')
				{
					return true;
				}
			}
			Alert.show("输入邮箱有误");
			return false;
		}
		
		public function passwordCheck():Boolean
		{
			if(view.password.text == view.rePassword.text)
			{
				return true;
			}
			else
			{
				Alert.show("两次密码不同");
				return false;
			}
		}
		
		private function regenerateCheckCode(event:MouseEvent):void
		{
			view.checkCodeLal.text = generateCheckCode();
		}
	}
}